import { useRef } from "react";
import { Image, message, Popconfirm, Button } from "antd";
import { PageContainer } from "@ant-design/pro-layout";
import ProForm, {
  ModalForm,
  ProFormRadio,
  ProFormDependency,
  ProFormTextArea,
  ProFormSelect,
  ProFormDigit,
} from "@ant-design/pro-form";
import useCommonTable from "@/hooks/useCommonTable";
import { history } from "umi";
import {
  fetchRefundsList,
  approval,
  pass,
  deliverChangeGoods,
} from "@/api/order";
import {
  goodsServiceTypeOptions,
  refundsStatusOptions,
  nameListOptions,
} from "@/const";

export default () => {
  const columns = [
    {
      title: "商品",
      dataIndex: "shop",
      search: false,
      render: (_, record) => {
        return (
          <>
            {record.articlesVOS?.map((item, index) => {
              return (
                <div
                  key={item.id}
                  style={{ display: "flex", marginBottom: 10 }}
                >
                  <Image width={80} height={80} src={item.picture} />
                  <div style={{ marginLeft: 8 }}>
                    <div>{item.title}</div>
                    <div>￥{item.unitPrice}</div>
                    <div>{item.quantity}</div>
                  </div>
                </div>
              );
            })}
          </>
        );
      },
    },
    {
      title: "状态",
      dataIndex: "status",
      valueType: "select",
      fieldProps: {
        options: refundsStatusOptions,
      },
    },
    {
      title: "订单号",
      dataIndex: "orderNum",
    },
    {
      title: "用户信息",
      dataIndex: "reciver",
      search: false,
      render: (_, record) => {
        return (
          <>
            <div>姓名：{record.userName}</div>
            <div>手机号：{record.phoneNum}</div>
            <div>
              收货地址：
              {record.province}
              {record.city}
              {record.area}
              {record.detail}
            </div>
          </>
        );
      },
    },
    {
      title: "交易金额",
      dataIndex: "refundPrice",
      search: false,
      render: (_, record) => {
        return <>￥{record.refundPrice}</>;
      },
    },
    {
      title: "类型",
      dataIndex: "goodsServiceType",
      valueType: "select",
      fieldProps: {
        options: goodsServiceTypeOptions,
      },
    },
    {
      title: "售后图片",
      dataIndex: "reciver",
      search: false,
      render: (_, record) => {
        const images = record.problemPicture?.split(",") || [];
        return (
          <>
            {images?.map((url, index) => {
              return (
                <div key={index} style={{ display: "flex", marginBottom: 10 }}>
                  <Image
                    width={80}
                    height={80}
                    src={url}
                    style={{ marginRight: 8 }}
                  />
                </div>
              );
            })}
          </>
        );
      },
    },
    {
      title: "售后原因",
      dataIndex: "refundReason",
      search: false,
    },
  ];

  const formRef = useRef();
  const renderAuditFormModal = (record, actionRef) => {
    const handleAddOrUpdate = async (fields) => {
      const postData = {
        ...fields,
        refundsId: record.id,
      };
      const res = await approval(postData);
      if (res.data) {
        message.success("审核成功");
        actionRef?.current.reload();
        return true; // 关闭弹框
      }
    };

    return (
      <ModalForm
        key="audit"
        labelCol={{
          span: 4,
        }}
        formRef={formRef}
        layout="horizontal"
        title="审核"
        width={600}
        trigger={
          <Button style={{ marginRight: 10 }} type="primary">
            审核
          </Button>
        }
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            formRef.current?.resetFields();
          },
        }}
        onFinish={async (values) => {
          return await handleAddOrUpdate(values);
        }}
        initialValues={{
          ...record,
        }}
      >
        <ProFormRadio.Group
          label="是否通过"
          name="status"
          options={[
            {
              value: 1,
              label: "通过",
            },
            {
              value: 4,
              label: "驳回",
            },
          ]}
          rules={[
            {
              required: true,
              message: "请选择是否通过",
            },
          ]}
        />
        <ProFormDependency name={["status"]}>
          {({ status }) => {
            return (
              status == 4 && (
                <ProFormTextArea
                  fieldProps={{
                    rows: 5,
                    showCount: true,
                    maxLength: 600,
                  }}
                  name="overruledReason"
                  label="原因"
                  placeholder="请输入驳回原因"
                  rules={[
                    {
                      required: true,
                      message: "请输入驳回原因",
                    },
                  ]}
                />
              )
            );
          }}
        </ProFormDependency>
      </ModalForm>
    );
  };

  // 换货===再次发货
  const renderSendModal = (record, actionRef) => {
    /* orderType 1=书籍 2=周边 3=积分 4=购物车 */
    /* articlesCategory 1=书籍 2=周边 */

    /* 1. orderType=1 直接展示芯片码*/
    /* 2. orderType=3 判断 articlesVOS 里面有articlesCategory=1的书籍 数量：quantity 展示芯片码*/
    /* 3. orderType=4 判断 articlesVOS 里面有articlesCategory=1的书籍 数量：quantity 展示芯片码*/

    let showCode = record.orderType == 1;
    if (record.orderType == 3 || record.orderType == 4) {
      showCode = record.articlesVOS?.some((item) => item.articlesCategory == 1);
    }
    // 能扫码的最大数量
    const quantity = record.articlesVOS
      ?.map((item) => item.quantity)
      .reduce((a, b) => a + b);

    return (
      <ModalForm
        title="换货"
        trigger={<Button type="primary">换货</Button>}
        onFinish={async (values) => {
          const res = await deliverChangeGoods({
            refundsId: record.id,
            addressId: record.addressId,
            orderId: record.orderId,
            orderCategory: record.orderType,
            ...values,
          });
          if (res.data) {
            message.success("发货成功");
            actionRef.current?.reload();
          }
        }}
      >
        <ProFormSelect
          name="name"
          label="商品描述"
          allowClear
          fieldProps={{
            options: nameListOptions,
          }}
          rules={[{ required: true, message: "请选择商品描述" }]}
        />
        <ProFormDigit
          label="包裹数量"
          name="quantity"
          placeholder="请输入包裹数量"
          min={1}
          rules={[{ required: true, message: "请输入包裹数量" }]}
        />
        <ProFormDigit
          label="包裹重量(kg)"
          name="weight"
          placeholder="请输入包裹重量"
          min={0.01}
          max={99999999}
          fieldProps={{
            precision: 2,
          }}
          rules={[{ required: true, message: "请输入包裹重量" }]}
        />
        <ProFormDigit
          label="包裹体积(m³)"
          name="volume"
          placeholder="请输入包裹体积"
          min={0.01}
          max={99999999}
          fieldProps={{
            precision: 2,
          }}
          rules={[{ required: true, message: "请输入包裹体积" }]}
        />

        {showCode && (
          <ProForm.Item
            label="芯片码"
            name="rasCodeList"
            rules={[{ required: true, message: "请扫码芯片码" }]}
          >
            <ScanRasCode quantity={quantity} />
          </ProForm.Item>
        )}
      </ModalForm>
    );
  };

  return (
    <PageContainer>
      {useCommonTable({
        title: "",
        renderAdd: () => {},
        columns,
        modalWidth: 400,
        fetchList: fetchRefundsList,
        actionColumnWidth: 200,
        showCheckbox: false,
        renderAction: (_, record, renderModalForm, actionRef) => {
          return (
            <>
              {/* 0:待审批-审核 1:待寄回 2:运输中 3:已完成 4:已驳回  */}
              {record.status == 0 && renderAuditFormModal(record, actionRef)}

              <>
                {record.status == 2 && (
                  <>
                    {/* goodsServiceType  0=退货 1=换货*/}
                    {record.goodsServiceType == 0 && (
                      <Popconfirm
                        key="ok"
                        title="确定收货?"
                        onConfirm={async () => {
                          const res = await pass({
                            orderId: record.orderId,
                            orderType: record.orderType,
                            userId: record.userId,
                            refundsId: record.id,
                            refundPrice: record.refundPrice,
                            wxOrderNum: record.wxOrderNum,
                          });
                          if (res.data) {
                            message.success("收货成功");
                            actionRef.current?.reload();
                          }
                        }}
                      >
                        <Button type="primary">收货</Button>
                      </Popconfirm>
                    )}

                    {record.goodsServiceType == 1 &&
                      renderSendModal(record, actionRef)}
                  </>
                )}
              </>
            </>
          );
        },
      })}
    </PageContainer>
  );
};
